package com.imooc.security.filter;

import com.imooc.security.log.AuditLog;
import com.imooc.security.log.AuditLogRepository;
import com.imooc.security.user.User;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @ClassName AuditLogInterceptor
 * @Description TODO 审计日志拦截器
 * @Author wushaopei
 * @Date 2021/5/1 18:02
 * @Version 1.0
 */
@Component
public class AuditLogInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AuditLogRepository auditLogRepository;

    /**
     * @Description TODO 前置处理，请求进来就进行记录
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        AuditLog log = new AuditLog();
        log.setMethod(request.getMethod());
        log.setPath(request.getRequestURI());
        User user = (User)request.getAttribute("user");
        if (user != null){
            log.setUsername(user.getUsername());
        }
        auditLogRepository.save(log);
        request.setAttribute("auditLogId", log.getId());

        return true;
    }

    /**
     * @Description TODO 后置处理，请求返回的时候进行记录
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

        Long auditLogId = (Long)request.getAttribute("auditLogId");
        AuditLog log = auditLogRepository.findById(auditLogId).get();
        log.setStatus(response.getStatus());
        // 响应时修改
        log.setModifyTime(new Date());
        auditLogRepository.save(log);
    }
}
